package com.souku.finance.application.http.retrofit;

import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.internal.$Gson$Types;
import com.souku.finance.application.bean.BaseBean;

import org.json.JSONObject;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import okhttp3.*;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Administrator on 2016/9/10.
 */
public abstract class BaseArrayCallback<T extends BaseBean> implements Callback<ResponseBody> {

    private String responseBody;
    private String data;
    private String error;
    private List<T> beans;

    public BaseArrayCallback() {
    }

    @Override
    public void onResponse(final Call<ResponseBody> call, final Response<ResponseBody> response) {

        try {
            if (response.body() != null) {
                responseBody = response.body().string();
                JSONObject jsonObject = new JSONObject(responseBody);
                BaseArrayCallback.this.error = jsonObject.optString("error");
                BaseArrayCallback.this.data = jsonObject.getString("data");
            } else {
                error = response.errorBody().string();
            }

            if (!TextUtils.isEmpty(error)) {
                onError();
            } else if (!TextUtils.isEmpty(data)) {
                Type genericSuperclass = getClass().getGenericSuperclass();
                if (genericSuperclass instanceof ParameterizedType) {
                    Type type = ((ParameterizedType) genericSuperclass).getActualTypeArguments()[0];
                    Type arrayType = $Gson$Types.newParameterizedTypeWithOwner(null
                            , ArrayList.class, type);
                    beans = new Gson().fromJson(data, arrayType);
                    onSuccess(beans);
                } else {
                    onError();
                }
            }

        } catch (final Exception e) {
            e.printStackTrace();
            onError();
        }

    }

    @Override
    public void onFailure(Call<ResponseBody> call, Throwable t) {
        onError();
    }

    public abstract void onSuccess(List<T> beans);

    public abstract void onError();
}
